package cn.tedu.egweibo4.controller;

import cn.tedu.egweibo4.common.respose.JsonResult;
import cn.tedu.egweibo4.common.respose.StatusCode;
import cn.tedu.egweibo4.mapper.UserMapper;
import cn.tedu.egweibo4.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo4.pojo.dto.UserRegDTO;
import cn.tedu.egweibo4.pojo.entity.User;
import cn.tedu.egweibo4.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpSession;
import java.util.Date;
@Api(tags = "用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @ApiOperation("注册功能")
    @PostMapping("reg")
    public JsonResult reg(@RequestBody @Validated UserRegDTO userRegDTO){
        log.debug("userRegDTO :" +userRegDTO );
        UserVO userVO =userMapper.selectUser(userRegDTO.getUsername());
        if (userVO!=null){
            return new JsonResult(StatusCode.USERNAME_ALREADY_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insertUser(user);
        return JsonResult.ok();
    }

    @ApiOperation("登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody  UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session ){
        UserVO userVO = userMapper.selectUser(userLoginDTO.getUsername());
//        if (userVO==null){
//            return new JsonResult(StatusCode.USERNAME_ERROR);
//        }
        if (userLoginDTO.getPassword().equals(userVO.getPassword())){
            session.setAttribute("user",userVO);
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.PASSWORD_ERROR);
    }
}
